package com.ruoyi.system.service.impl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.MealStatisticsDTO;
import com.ruoyi.system.domain.dto.MyOrdersDTO;
import com.ruoyi.system.domain.dto.TrainingOrderStatisticsDTO;
import com.ruoyi.system.domain.dto.UnfilledMealOrderDTO;
import com.ruoyi.system.domain.vo.MealStatisticsBO;
import com.ruoyi.system.mapper.EmployeeMapper;
import com.ruoyi.system.mapper.MealOrderMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.TrainingMapper;
import com.ruoyi.system.service.IMealOrderService;
import com.ruoyi.system.utils.DateRange;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

/**
 * 订餐管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-15
 */
@Service
public class MealOrderServiceImpl implements IMealOrderService {
    @Autowired
    private MealOrderMapper mealOrderMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private TrainingMapper trainingMapper;
    @Autowired
    private SysUserMapper userMapper;
    private static final Logger log = LoggerFactory.getLogger(MealOrderServiceImpl.class);
    /**
     * 查询订餐管理
     *
     * @param id 订餐管理主键
     * @return 订餐管理
     */
    @Override
    public MealOrder selectMealOrderById(Long id) {
        return mealOrderMapper.selectMealOrderById(id);
    }

    /**
     * 查询订餐管理列表
     *
     * @param mealOrder 订餐管理
     * @return 订餐管理
     */
    @Override
    public List<MealOrder> selectMealOrderList(MealOrder mealOrder) {
        return mealOrderMapper.selectMealOrderList(mealOrder);
    }

    /**
     * 新增订餐管理
     *
     * @param mealOrder 订餐管理
     * @return 结果
     */
    @Override
    public int insertMealOrder(MealOrder mealOrder) {
        // 插入订餐主表记录（如果需要的话）
        // 注意：根据当前数据库设计，meal_order表中每条记录代表一个员工在某一天某一餐的订餐情况
        // 所以实际上不需要插入主表记录，只需要插入详情记录即可

        int insertedCount = 0;

        // 插入订餐详情记录
        if (mealOrder.getMealDetails() != null && !mealOrder.getMealDetails().isEmpty()) {
            for (MealOrderVO.MealDetail detail : mealOrder.getMealDetails()) {
                // 创建一个新的MealOrder.MealDetail对象用于数据库操作
                MealOrder.MealDetail dbDetail = new MealOrder.MealDetail();
                dbDetail.setEmpId(mealOrder.getEmpId());
                dbDetail.setTrainingId(mealOrder.getTrainingId());
                dbDetail.setMealDate(detail.getMealDate());
                dbDetail.setMealType(detail.getMealType());
                // 确保isOrdered是Integer类型
                dbDetail.setIsOrdered(detail.getIsOrdered());

                // 插入订餐详情
                int result = mealOrderMapper.insertMealDetail(dbDetail);
                if (result > 0) {
                    insertedCount++;
                }
            }
        }

        return insertedCount;
    }
    /**
     * 修改订餐管理
     *
     * @param mealOrder 订餐管理
     * @return 结果
     */
    @Override
    public int updateMealOrder(MealOrder mealOrder) {
        log.info("开始更新订餐信息: id={}, empId={}, trainingId={}, mealDetailsSize={}",
                mealOrder.getId(), mealOrder.getEmpId(), mealOrder.getTrainingId(),
                mealOrder.getMealDetails() != null ? mealOrder.getMealDetails().size() : 0);

        // 检查必要的字段是否存在
        if (mealOrder.getEmpId() == null || mealOrder.getTrainingId() == null) {
            log.error("更新订餐信息失败：empId或trainingId为空，id={}, empId={}, trainingId={}",
                    mealOrder.getId(), mealOrder.getEmpId(), mealOrder.getTrainingId());
            throw new RuntimeException("员工ID和培训ID不能为空");
        }

        // 先删除该员工在该培训中的所有订餐记录
        int deletedCount = mealOrderMapper.deleteMealDetailsByEmpIdAndTrainingId(
                mealOrder.getEmpId(), mealOrder.getTrainingId());
        log.info("删除了 {} 条旧的订餐记录，empId={}, trainingId={}", deletedCount, mealOrder.getEmpId(), mealOrder.getTrainingId());

        // 插入新的订餐详情记录
        int insertedCount = 0;
        if (mealOrder.getMealDetails() != null && !mealOrder.getMealDetails().isEmpty()) {
            log.info("准备插入 {} 条新的订餐记录", mealOrder.getMealDetails().size());
            for (MealOrderVO.MealDetail detail : mealOrder.getMealDetails()) {
                // 创建一个新的MealOrder.MealDetail对象用于数据库操作
                MealOrder.MealDetail dbDetail = new MealOrder.MealDetail();
                dbDetail.setEmpId(mealOrder.getEmpId());
                dbDetail.setTrainingId(mealOrder.getTrainingId());
                dbDetail.setMealDate(detail.getMealDate());
                dbDetail.setMealType(detail.getMealType());
                // 确保isOrdered是Integer类型
                dbDetail.setIsOrdered(detail.getIsOrdered());

                log.debug("准备插入订餐详情: trainingId={}, empId={}, date={}, type={}, ordered={}",
                        dbDetail.getTrainingId(), dbDetail.getEmpId(), dbDetail.getMealDate(),
                        dbDetail.getMealType(), dbDetail.getIsOrdered());

                // 插入订餐详情
                int result = mealOrderMapper.insertMealDetail(dbDetail);
                if (result > 0) {
                    insertedCount++;
                }
                log.debug("插入订餐详情结果: result={}", result);
            }
        }

        log.info("更新完成: 删除 {} 条记录，插入 {} 条记录", deletedCount, insertedCount);
        return insertedCount; // 返回插入的记录数作为成功标识
    }

    @Override
    public int updateOrder(MealOrder mealOrder) {
        return mealOrderMapper.updateMealOrder(mealOrder);
    }

    /**
     * 批量删除订餐管理
     *
     * @param ids 需要删除的订餐管理主键
     * @return 结果
     */
    @Override
    public int deleteMealOrderByIds(Long[] ids) {
        return mealOrderMapper.deleteMealOrderByIds(ids);
    }

    /**
     * 删除订餐管理信息
     *
     * @param id 订餐管理主键
     * @return 结果
     */
    @Override
    public int deleteMealOrderById(Long id) {
        return mealOrderMapper.deleteMealOrderById(id);
    }

    @Override
    public String importMealOrder(List<MealOrder> mealOrderList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(mealOrderList) || mealOrderList.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (MealOrder mealOrder : mealOrderList) {
            try {
                // 验证数据
                if (!validateMealOrder(mealOrder)) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、订餐记录 数据格式不正确");
                    continue;
                }

                // 解析电话号码和培训名称
                if (mealOrder.getRemark() != null && mealOrder.getRemark().contains("|")) {
                    String[] parts = mealOrder.getRemark().split("\\|");
                    String phone = parts[0];
                    String trainingName = parts[1];

                    // 查询培训ID
                    List<Training> trainings = trainingMapper.selectTrainingListByTrainingName(trainingName);
                    if (trainings != null && !trainings.isEmpty()) {
                        mealOrder.setTrainingId(trainings.get(0).getId());
                    } else {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、未找到培训名称为 " + trainingName + " 的培训");
                        continue;
                    }

                    // 查询员工ID
                    Employee employee = employeeMapper.selectEmployeeByPhone(phone);
                    if (employee != null) {
                        mealOrder.setEmpId(employee.getId());
                    } else {
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、未找到电话号码为 " + phone + " 的员工");
                        continue;
                    }
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、电话号码或培训名称信息不完整");
                    continue;
                }

                // 插入新数据
                mealOrder.setCreateBy(operName);
                mealOrderMapper.insertMealOrder(mealOrder);
                successNum++;
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、订餐记录导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
     /**
     * 验证订餐数据格式
     */
    /**
     * 验证订餐数据格式
     */
    /**
     * 验证订餐数据格式
     */
    private boolean validateMealOrder(MealOrder mealOrder) {
        // 对于导入的数据，我们只验证必要字段
        // trainingId 和 empId 在导入时可能还未设置，将在后续处理中关联

        // 验证是否订餐字段只能是0或1
        if (mealOrder.getIsOrdered() != null && mealOrder.getIsOrdered() != 0 && mealOrder.getIsOrdered() != 1) {
            return false;
        }

        // 验证餐别
        if (mealOrder.getMealType() != null &&
                !("午餐".equals(mealOrder.getMealType()) || "晚餐".equals(mealOrder.getMealType()))) {
            return false;
        }

        // 验证用餐日期
        if (mealOrder.getMealDate() == null) {
            return false;
        }

        return true;
    }
    /**
     * 查询订餐管理VO列表
     *
     * @param mealOrderVO 订餐管理VO
     * @return 订餐管理VO集合
     */
    @Override
    public List<MealOrderVO> selectMealOrderVOList(MealOrderVO mealOrderVO) {
        return mealOrderMapper.selectMealOrderVOList(mealOrderVO);
    }

    /**
     * 查询培训订餐人数
     * @param year 年
     * @param month 月
     * @param day 日
     * @param mealType 订餐类型
     * @return 培训订餐人数
     */
    @Override
    public List<MealStatisticsBO> getMealStatistics(Integer year, Integer month, Integer day, String mealType) {
        // 确定时间范围
        DateRange dateRange = resolveDateRange(year, month, day);

        // 查询数据
        List<MealStatisticsDTO> statistics = mealOrderMapper.selectMealStatistics(
                dateRange.getStartDate(), dateRange.getEndDate(), mealType);

        // 转换为VO
        return convertToVO(statistics, mealType);
    }

    // 处理时间范围
    private DateRange resolveDateRange(Integer year, Integer month, Integer day) {
        LocalDate startDate;
        LocalDate endDate;

        if (day != null) {
            // 按日查询
            startDate = LocalDate.of(year, month, day);
            endDate = startDate;
        } else if (month != null) {
            // 按月查询
            startDate = LocalDate.of(year, month, 1);
            endDate = startDate.with(TemporalAdjusters.lastDayOfMonth());
        } else {
            // 默认处理，默认当年当月
            LocalDate now = LocalDate.now();
            startDate = LocalDate.of(now.getYear(), now.getMonthValue(), 1);
            endDate = startDate.with(TemporalAdjusters.lastDayOfMonth());
        }

        // 将LocalDate转换为String格式
        String startStr = startDate.toString();
        String endStr = endDate.toString();

        // 创建DateRange对象
        return new DateRange(startStr, endStr);
    }

    @Override
    public List<MealOrderExportVO> exportData() {
        return Collections.emptyList();
    }

    /**
     * 查询订餐管理导出VO列表
     *
     * @param mealOrderVO 订餐管理VO
     * @return 订餐管理导出VO集合
     */
    @Override
    public List<MealOrderExportVO> selectMealOrderExportVOList(MealOrderVO mealOrderVO) {
        // 获取完整的 MealOrderVO 数据
        List<MealOrderVO> voList = mealOrderMapper.selectMealOrderVOList(mealOrderVO);

        // 使用Map来去重，key为(培训名称+员工编号)
        Map<String, MealOrderExportVO> exportMap = new LinkedHashMap<>();

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        int seq = 1;
        for (MealOrderVO vo : voList) {
            // 创建唯一标识符
            String key = vo.getTrainingName() + "_" + vo.getEmployeeNo();

            // 如果还没有这个员工的记录，创建新的
            if (!exportMap.containsKey(key)) {
                MealOrderExportVO exportVO = new MealOrderExportVO();
                exportVO.setSeq(seq++);
                exportVO.setTrainingName(vo.getTrainingName());
                exportVO.setEmployeeName(vo.getEmployeeName());
                exportVO.setEmployeeNo(vo.getEmployeeNo());
                exportVO.setDept(vo.getDept());
                exportVO.setPhone(vo.getPhone());
                exportVO.setEmail(vo.getEmail());
                exportVO.setStartDate(vo.getStartDate());
                exportVO.setEndDate(vo.getEndDate());

                // 设置培训时间
                if (vo.getStartDate() != null && vo.getEndDate() != null) {
                    exportVO.setTrainingTime(dateFormat.format(vo.getStartDate()) + "至" + dateFormat.format(vo.getEndDate()));
                }

                // 转换性别
                if (vo.getSex() != null) {
                    exportVO.setSex(vo.getSex().equals("1") ? "男" : "女");
                }

                // 初始化用餐情况Map
                exportVO.setDailyMeals(new HashMap<>());

                exportMap.put(key, exportVO);
            }

            // 获取已存在的记录
            MealOrderExportVO exportVO = exportMap.get(key);

            // 处理用餐详情
            if (vo.getMealDetails() != null) {
                for (MealOrderVO.MealDetail detail : vo.getMealDetails()) {
                    String dateStr = dateFormat.format(detail.getMealDate());
                    String mealKey = dateStr + "_" + detail.getMealType();
                    String value = detail.getIsOrdered() != null ? (detail.getIsOrdered() == 1 ? "是" : "否") : "未填写";
                    exportVO.getDailyMeals().put(mealKey, value);
                }
            }
        }




        // 转换为列表
        return new ArrayList<>(exportMap.values());
    }

    /**
     * 按培训分组获取导出数据
     *
     * @param mealOrderVO 查询条件
     * @return 按培训分组的导出数据
     */
    @Override
    public Map<String, List<MealOrderExportVO>> selectGroupedExportData(MealOrderVO mealOrderVO) {
        List<MealOrderExportVO> exportList = selectMealOrderExportVOList(mealOrderVO);

        // 按培训名称分组
        Map<String, List<MealOrderExportVO>> groupedData = new LinkedHashMap<>();
        for (MealOrderExportVO exportVO : exportList) {
            String trainingName = exportVO.getTrainingName();
            if (!groupedData.containsKey(trainingName)) {
                groupedData.put(trainingName, new ArrayList<>());
            }
            groupedData.get(trainingName).add(exportVO);
        }

        return groupedData;
    }


    private List<MealStatisticsBO> convertToVO(List<MealStatisticsDTO> dtos, String mealType) {
        Map<String, MealStatisticsBO> voMap = new LinkedHashMap<>();

        for (MealStatisticsDTO dto : dtos) {
            MealStatisticsBO vo = voMap.computeIfAbsent(dto.getTrainingName(),
                    k -> new MealStatisticsBO(mealType, dto.getTrainingName()));

            vo.setOrderTotal(vo.getOrderTotal() + dto.getCount());

            // 判断县公司逻辑
            if (isCountyCompany(dto.getDistrict())) {
                vo.setDistrictOrderTotal(vo.getDistrictOrderTotal() + dto.getCount());
            }

            vo.addDetail(new MealStatisticsBO.DistrictDetail(dto.getDistrict(), dto.getCount()));
        }

        return new ArrayList<>(voMap.values());
    }

    private boolean isCountyCompany(String district) {
        // 区县公司判断：不包含市公司、不包含濂溪，或者包含分公司
        return district != null &&
                !"市公司".equals(district) &&
                !district.contains("濂溪") &&
                district.contains("分公司");
    }
    /**
     * 获取单次培训午、晚餐订餐情况
     */
    @Override
    public AjaxResult getTrainingOrder(String trainingName) {
        List<TrainingOrderStatisticsDTO> result = mealOrderMapper.selectTrainingOrder(trainingName);
        return AjaxResult.success(result);
    }
    /**
     * 根据员工ID和培训ID删除订餐详情
     *
     * @param empId 员工ID
     * @param trainingId 培训ID
     * @return 结果
     */
    @Override
    public int deleteMealDetailsByEmpIdAndTrainingId(Long empId, Long trainingId) {
        return mealOrderMapper.deleteMealDetailsByEmpIdAndTrainingId(empId, trainingId);
    }
    /**
     * 根据员工ID和培训ID查询订餐记录
     *
     * @param empId 员工ID
     * @param trainingId 培训ID
     * @return 订餐记录列表
     */
    @Override
    public List<MealOrderVO> selectByEmpAndTraining(Long empId, Long trainingId) {
        return mealOrderMapper.selectByEmpAndTraining(empId, trainingId);
    }


    /**
     * 查找目标订单
     */
    @Override
    public MealOrder findTargetOrder(List<MealOrder> list, String currentDate, String mealType, SimpleDateFormat sdf) {
        for (MealOrder order : list) {
            if (order.getMealDate() != null &&
                    sdf.format(order.getMealDate()).equals(currentDate) &&
                    mealType.equals(order.getMealType()) &&
                    Integer.valueOf(1).equals(order.getIsOrdered())) {
                return order;
            }
        }
        return null;
    }

    /**
     * 根据当前时间判断是午餐还是晚餐时间
     * @param now 当前时间
     * @return "午餐" 或 "晚餐" 或 null(非用餐时间)
     */
    @Override
    public String getCurrentMealType(Date now) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);

        // 更精确的时间判断逻辑
        // 午餐核销时间: 11:00-14:00，晚餐核销时间: 17:00-20:00
        if ((hour == 11 && minute >= 0) || (hour == 12) || (hour == 13) || (hour == 14 && minute <= 0)) {
            return "午餐";
        } else if ((hour == 17 && minute >= 0) || (hour == 18) || (hour == 19) || (hour == 20 && minute <= 0)) {
            return "晚餐";
        }

        return null; // 非用餐核销时间
    }
    /**
     * 查询未填写订餐信息的记录
     * @return 未填写订餐信息列表
     */
    @Override
    public List<UnfilledMealOrderDTO> getUnfilledMealOrders(Long empId) {
        return mealOrderMapper.selectUnfilledMealOrders(empId);
    }

    @Override
    public MyOrdersDTO getMyOrders(Long empId){
        List<OneOrderItem> orderItems = mealOrderMapper.selectMyOrders(empId);
        MyOrdersDTO result = new MyOrdersDTO();
        result.setEmpId(empId);
        result.setAllItems(orderItems);
        return result;
    }

    @Override
    public int alterMealOrderStatus(Long id, Integer status){
        return mealOrderMapper.updateMealOrderStatus(id,status);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult importMealOrderTable(List<MealOrderTable> orderList, String trainingName, String start, String end, boolean updateSupport) {
        try {
            // 参数校验
            if (StringUtils.isBlank(trainingName) || StringUtils.isBlank(start) || StringUtils.isBlank(end)) {
                return AjaxResult.error("参数不能为空");
            }

            // 解析培训时间
            LocalDate startDate;
            LocalDate endDate;
            try {
                startDate = LocalDate.parse(start);
                endDate = LocalDate.parse(end);
            } catch (Exception e) {
                return AjaxResult.error("日期格式错误，应为 yyyy-MM-dd 格式");
            }

            // 验证日期范围
            if (startDate.isAfter(endDate)) {
                return AjaxResult.error("开始日期不能晚于结束日期");
            }

            // 根据培训名称查询培训信息
            Training training = trainingMapper.selectByTrainingName(trainingName);
            if (training == null) {
                return AjaxResult.error("培训不存在: " + trainingName);
            }

            ImportResult importResult = processOrderList(orderList, training, startDate, endDate, updateSupport);

            return buildResponse(importResult);
        } catch (Exception e) {
            log.error("导入订餐表失败", e);
            return AjaxResult.error("导入失败: " + e.getMessage());
        }
    }

    /**
     * 处理订单列表
     */
    private ImportResult processOrderList(List<MealOrderTable> orderList, Training training,
                                          LocalDate startDate, LocalDate endDate, boolean updateSupport) {
        ImportResult result = new ImportResult();

        // 遍历Excel数据列表
        for (int i = 0; i < orderList.size(); i++) {
            MealOrderTable orderTable = orderList.get(i);
            int rowNumber = i + 2;

            try {
                processSingleOrder(orderTable, rowNumber, training, startDate, endDate, updateSupport, result);
            } catch (Exception e) {
                String errorMsg = String.format("处理第%d行数据时发生错误: %s", rowNumber, e.getMessage());
                result.addError(errorMsg);
                log.error(errorMsg, e);

                // 如果不支持更新，遇到错误直接返回
                if (!updateSupport) {
                    break;
                }
            }
        }

        return result;
    }

    /**
     * 处理单个订单
     */
    private void processSingleOrder(MealOrderTable orderTable, int rowNumber, Training training,
                                    LocalDate startDate, LocalDate endDate, boolean updateSupport,
                                    ImportResult result) throws Exception {
        // 跳过空行
        if (StringUtils.isBlank(orderTable.getEmployeeNo())) {
            result.incrementSkipCount();
            return;
        }

        // 根据手机号查询用户
        SysUser user = userMapper.selectUserByPhoneNumber(orderTable.getPhoneNumber());

        // 验证用户手机号和姓名是否匹配
        if (user != null && StringUtils.isNotBlank(orderTable.getName())) {
            // 检查姓名是否匹配，如果不匹配则记录错误并跳过
            if (!orderTable.getName().equals(user.getNickName())) {
                String errorMsg = String.format("第%d行：Excel中的姓名\"%s\"与系统中的姓名\"%s\"不匹配",
                        rowNumber, orderTable.getName(), user.getNickName());
                result.addError(errorMsg);
                result.incrementSkipCount();
                log.warn(errorMsg);
                return;
            }
        }

        user = handleUser(orderTable, user, updateSupport, result);
        if (user == null) {
            result.incrementSkipCount();
            return;
        }

        // 删除该用户在该培训时间范围内的所有订餐记录
        mealOrderMapper.deleteByIdAndDateRange(training.getId(), user.getUserId(), startDate, endDate);

        // 生成新的订餐记录
        List<MealOrder> orders = generateMealOrders(training.getId(), user.getUserId(), startDate, endDate);
        for (MealOrder order : orders) {
            mealOrderMapper.insertMealOrder(order);
        }

        result.incrementSuccessCount();
    }

    /**
     * 处理用户信息
     */
    private SysUser handleUser(MealOrderTable orderTable, SysUser user, boolean updateSupport, ImportResult result) throws Exception {
        if (user == null) {
            // 如果用户不存在且不允许更新，则跳过
            if (!updateSupport) {
                String errorMsg = String.format("%s在系统中不存在且未启用更新模式，已跳过", orderTable.getName());
                result.addError(errorMsg);
                return null;
            }
            // 创建新用户
            user = createNewUser(orderTable);
            userMapper.insertUser(user);
        } else {
            // 如果用户存在且允许更新，则更新电话和邮箱
            if (updateSupport) {
                updateUserFields(user, orderTable);
            }
        }
        return user;
    }

    /**
     * 更新用户字段
     */
    private void updateUserFields(SysUser user, MealOrderTable orderTable) {
        boolean updated = false;

        if (StringUtils.isNotBlank(orderTable.getPhoneNumber()) &&
                !orderTable.getPhoneNumber().equals(user.getPhonenumber())) {
            user.setPhonenumber(orderTable.getPhoneNumber());
            updated = true;
        }

        if (StringUtils.isNotBlank(orderTable.getEmail()) &&
                !orderTable.getEmail().equals(user.getEmail())) {
            user.setEmail(orderTable.getEmail());
            updated = true;
        }

        if (StringUtils.isNotBlank(orderTable.getEmployeeNo()) &&
                !orderTable.getEmployeeNo().equals(user.getRemark())) {
            user.setRemark(orderTable.getEmployeeNo());
            updated = true;
        }

        if (updated) {
            userMapper.updateUser(user);
        }
    }

    /**
     * 构建响应结果
     */
    private AjaxResult buildResponse(ImportResult result) {
        String resultMsg = String.format("成功处理 %d 条记录，跳过 %d 条记录。",
                result.getSuccessCount(), result.getSkipCount());

        if (!result.getErrors().isEmpty()) {
            resultMsg += " 详细信息：" + String.join("；", result.getErrors());
        }

        // 根据处理结果返回不同状态
        if (result.getSuccessCount() > 0) {
            if (!result.getErrors().isEmpty()) {
                // 部分成功
                return AjaxResult.warn(resultMsg);
            } else {
                // 全部成功
                return AjaxResult.success(resultMsg);
            }
        } else {
            // 全部失败
            return AjaxResult.error("导入失败：" + resultMsg);
        }
    }


    // 创建新用户
    private SysUser createNewUser(MealOrderTable orderTable) {
        SysUser user = new SysUser();
        user.setUserName(orderTable.getPhoneNumber());
        user.setNickName(orderTable.getName());
        user.setRemark(orderTable.getEmployeeNo());
        user.setPhonenumber(orderTable.getPhoneNumber());
        user.setEmail(orderTable.getEmail());
        user.setCreateTime(new Date());
        // 设置默认密码
        user.setPassword(SecurityUtils.encryptPassword("123456"));
        return user;
    }

    // 生成订餐记录
    private List<MealOrder> generateMealOrders(Long trainingId, Long userId, LocalDate start, LocalDate end) {
        List<MealOrder> list = new ArrayList<>();
        LocalDate current = start;

        while (!current.isAfter(end)) {
            // 午餐
            MealOrder lunch = new MealOrder();
            lunch.setTrainingId(trainingId);
            lunch.setEmpId(userId);
            lunch.setMealDate(java.sql.Date.valueOf(current));  // 转换为 java.sql.Date
            lunch.setMealType("午餐");
            lunch.setIsOrdered(3);
            lunch.setCreateTime(new Date());
            list.add(lunch);

            // 晚餐
            MealOrder dinner = new MealOrder();
            dinner.setTrainingId(trainingId);
            dinner.setEmpId(userId);
            dinner.setMealDate(java.sql.Date.valueOf(current));
            dinner.setMealType("晚餐");
            dinner.setIsOrdered(3);
            dinner.setCreateTime(new Date());
            list.add(dinner);

            current = current.plusDays(1);
        }
        return list;
    }
}

